package servlet;

import entity.News;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import service.NewsDaoService;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.Date;


@WebServlet(urlPatterns = "/saveData")
public class SaveDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String data = request.getParameter("data");
        String decodedText = URLDecoder.decode(data, StandardCharsets.UTF_8);
        System.out.println(decodedText);

        String savePath = request.getServletContext().getRealPath("/md");  //存储路径
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        long currentTimeMillis = System.currentTimeMillis();
        FileWriter out = new FileWriter(savePath + "/" + currentTimeMillis + ".md", StandardCharsets.UTF_8);
        out.write(decodedText);
        out.flush();
        out.close();
        response.getWriter().write("success");

        Date date = new Date();
        NewsDaoService nds = new NewsDaoService();

        String title = request.getParameter("title");
        String type = request.getParameter("type");
        String photo = request.getParameter("photo");
        //图片保存处理


        String tags = request.getParameter("tags");
        String uname = request.getParameter("uname");
        String uid = request.getParameter("uid");
        String state = request.getParameter("state");
        News news = new News();
        news.setNewsId("News"+System.currentTimeMillis());
        news.setUsername(uname);
        news.setUserId(Integer.valueOf(uid));
        news.setCreateTime(new Timestamp(date.getTime()));
        news.setNewsTitle(title);
        news.setType(Integer.parseInt(type));
        news.setIsDelete(0);
        news.setTotalView(0);
        news.setTags(tags);
        news.setNewsPic(photo);
        news.setIsDelete(0);
        news.setLinks(0);
        news.setState(Integer.parseInt(state));
        news.setNewsText(currentTimeMillis+".md");
        nds.createNews(news);

    }
}
